<?php

namespace app\zyhsmarketing\lib;

use app\zyhsapi\model\marketing\ZyhsHuaweiMarketingData;
use app\zyhsapi\model\marketing\ZyhsMarketingCallbackRecode;
use app\zyhsapi\service\CacheZyhs;
use think\Db;
use XznsTools\curl\Curl;

class HuaweiMarketing
{
    private $clientId = '1377522412639259392';
    private $clientSecret = 'BCB616B3972E6F1BFBCD9660B3509B5128A9F8881C209AA3EEF5C9DF9A1BBA29';

    private $getTokenUrl = 'https://connect-api.cloud.huawei.com/api/oauth2/v1/token';

    private $marketingCallbackUrl = 'https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate';

    /**
     * token 缓存key
     * @var string
     */
    private $tokenCacheKey = 'marketing:callback_token:huawei';

    /**
     * token 信息
     * @var string
     */
    private $token = '';

    public function getToken()
    {
        if ($this->token)
        {
            return $this->token;
        }

        $resToken = CacheZyhs::get($this->tokenCacheKey);
        if ($resToken)
        {
            $this->token = $resToken;
            return $resToken;
        }

        $resTokenData = Curl::request($this->getTokenUrl, [
            'grant_type' => 'client_credentials',
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
        ], 'POST', [], 'json');

        if ($resTokenData['success'] && isset($resTokenData['data']['access_token']) && $resTokenData['data']['access_token'])
        {
            $expiresIn = $resTokenData['data']['expires_in'] > 3600 ? $resTokenData['data']['expires_in'] - 3600 : $resTokenData['data']['expires_in'];

            CacheZyhs::set($this->tokenCacheKey, $resTokenData['data']['access_token'], $expiresIn);

            $this->token = $resTokenData['data']['access_token'];

            return $this->token;
        } else
        {
            return '';
        }
    }

    /**
     * 华为 Marketing API 回传转化数据
     * @param string $oaid
     * @param int $uid 用户uid
     * @param int $targetType 转化指标 1=>激活 2=>注册 3=>充值
     * @return void
     */
    public function callBack(string $oaid, int $uid, int $targetType)
    {
        try
        {
            $nowTime = time();
            $zyhsHuaweiMarketingDataModel = new ZyhsHuaweiMarketingData();
            $data = $zyhsHuaweiMarketingDataModel->where(['oaid' => $oaid, 'end_time' => ['>', $nowTime]])
                ->column('appid,callback', 'task_id');
            if ($data)
            {   // 转化成功
                $zyhsMarketingCallbackRecodeModel = new ZyhsMarketingCallbackRecode();
                foreach ($data as $taskId => $taskData)
                {   //  开始回传
                    $token = $this->getToken();
                    switch ($targetType)
                    {
                        case 2:
                            $actionType = 7;
                            break;
                        case 3:
                            $actionType = 4;
                            break;
                        default:
                            $actionType = 1;
                    }
                    $body = [
                        'appId' => $taskData['appid'],
                        'deviceIdType' => 'OAID',
                        'deviceId' => $oaid,
                        'actionTime' => $nowTime * 1000,
                        'actionType' => $actionType,
                        'callBack' => $taskData['callback'],
                    ];

                    $resData = Curl::request($this->marketingCallbackUrl, $body, 'POST', [
                        'headers' => [
                            'Content-Type' => 'application/json;charset=UTF-8',
                            'client_id' => $this->clientId,
                            'Authorization' => "Bearer {$token}",
                        ],
                    ], 'json');

                    if (!$resData['success'] || !isset($resData['data']['code']) || $resData['data']['code'] !== 0)
                    {   // 回传失败
                        Db::table('good_wechat.zyhs_marketing_callback_error')->insert([
                            'mobile_type' => 5, // 华为=>5 小米=>4 vivo=>3 oppo=>2
                            'target_type' => $targetType,
                            'oaid' => $oaid,
                            'extend' => json_encode($resData, JSON_UNESCAPED_UNICODE),
                        ]);
                    } else
                    {   // 添加 回传 记录
                        $zyhsMarketingCallbackRecodeModel->insert([
                            'task_id' => $taskId,
                            'oaid' => $oaid,
                            'uid' => $uid,
                            'type' => 5,
                            'target_type' => $targetType,   // 转化指标 1=>激活 2=>注册 3=>充值
                            'create_time' => $nowTime,
                        ]);
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }
}